# -*- coding: UTF-8 -*-
from . import api
from flask import render_template, request, send_file, make_response, redirect, jsonify
from app import util, redis
from dbConnection.MysqlConn import Mysql
import time, requests, json, re
appid = 'wx087bed01c194a785'
secret = 'e19da6efb5b79d404ef807ea8e113b2c'


# 微信网页授权
@api.route('/MP_verify_uL7H0jkV7p6StJje.txt')
def get_text():
    file_object = open('/home/MP_verify_uL7H0jkV7p6StJje.txt')
    try:
        content = file_object.read()
    finally:
        file_object.close()
    response = make_response(content)
    response.headers['Content-Disposition'] = 'attachment; filename=MP_verify_uL7H0jkV7p6StJje.txt'
    return response


# 登陆页面(公众号测试)
@api.route('/admin/get_user_wash')
def test_gzh():
    print '00'
    url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx087bed01c194a785&redirect_uri=http://5ic.me/wash/orders.html&response_type=code&scope=snsapi_base&state=1#wechat_redirect'
    return redirect(url)


# 获取openid
@api.route('/user/get_user_open', methods=['post'])
def get_user_open():
    code = request.values.get('code')
    price = request.values.get('price')
    print code
    data = {}
    try:
        url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code' % (appid, secret, code)
        res = requests.get(url)
        s = json.loads(res.text)
        print s
        if res.status_code == 200:
            if s['openid']:
                data['status'] = 1
                con = get_user_exist(s['openid'])
                redis.set(str(s['openid']), s['access_token'], ex=7000)
                if con:
                    update_user_wx(s['access_token'], s['openid'])
                    data['uid'] = con['uid']
                    data['bid'] = con['bid']
                else:
                    data['uid'] = insert_user(s['access_token'], s['openid'])
                    data['bid'] = 0
                data['card'] = s['openid']
                if price:
                    cons = get_price_list()
                    data['money'] = cons['modelPrice'] if cons else 0
            else:
                data['status'] = 2
        else:
            data['status'] = 0
    except Exception as e:
        print e
        data['status'] = 500
    print data
    return util.to_json(data)


# 获取洗车价格列表
def get_price_list():
    sql = "select modelPrice FROM wash_model where m_type = 1 AND status = 1"
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 查询用户openid是否注册
def get_user_exist(openid):
    sql = "select uid, bid from car_users WHERE wxOpenId = '%s'" % openid
    mysql = Mysql()
    res = mysql.getOne(sql, None)
    mysql.dispose()
    return res


# 更新用户信息
def update_user_wx(token, openid):
    data = get_user_info(token, openid)
    if len(data) < 1:
        return 0
    flag = 0
    mysql = Mysql()
    try:
        sql = "update car_users SET wxNickName = '%s', wxHeadImg = '%s' WHERE wxOpenId = '%s'" % (filter_emoji(data['nickname'],restr=''), data['headimgurl'], openid)
        mysql.update(sql, None)
    except Exception as e:
        print e
        if flag < 1:
            sql = "update car_users SET wxNickName = '%s', wxHeadImg = '%s' WHERE wxOpenId = '%s'" % ('', data['headimgurl'], openid)
            mysql.update(sql, None)
        flag += 1
    mysql.dispose()


# 注册用户
def insert_user(token, openid):
    data = get_user_info(token, openid)
    if len(data) < 1:
        return 0
    nickname = data['nickname']
    mysql = Mysql()
    flag = 0
    try:
        sql = "insert INTO car_users(wxOpenId, wxNickName, wxHeadImg, addTime) VALUES ('%s', '%s', '%s', now())"\
              % (data['openid'], filter_emoji(nickname,restr=''), data['headimgurl'])
        res = mysql.insertOne(sql, None)
    except Exception as e:
        print e
        if flag < 1:
            sql = "insert INTO car_users(wxOpenId, wxNickName, wxHeadImg, addTime) VALUES ('%s', '%s', '%s', now())"\
                  % (data['openid'], '', data['headimgurl'])
            res = mysql.insertOne(sql, None)
        flag += 1
    mysql.dispose()
    return res


# 请求接口
@api.route('/user/get_detail')
def get_detail():
    code = request.args.get('code')
    get_wy(code)
    return render_template('admin/login.html')


# 获取网页授权access_token
def get_wy(code):
    try:
        url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code' % (appid, secret, code)
        res = requests.get(url)
        s = json.loads(res.text)
        get_user_info(s['access_token'], s['openid'])
    except Exception as e:
        print e


# 获取关注用户的信息
def get_user_info(token, openid):
    data = {}
    try:
        url = 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN' % (token, openid)
        res = requests.get(url)
        if res.status_code == 200:
            dd = json.dumps(res.text, ensure_ascii=False)
            con = dd.encode('ISO-8859-1')
            s = json.loads(con)
            ss = eval(str(s).encode('utf-8'))
            if ss['nickname']:
                data = ss
    except Exception as e:
        print e
    return data


def filter_emoji(desstr,restr=''):
    try:
        co = re.compile(u'[\U00010000-\U0010ffff]')
    except re.error:
        co = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
    return co.sub(restr, desstr)


emoji_pattern = re.compile(
    u"(\ud83d[\ude00-\ude4f])|"  # emoticons
    u"(\ud83c[\udf00-\uffff])|"  # symbols & pictographs (1 of 2)
    u"(\ud83d[\u0000-\uddff])|"  # symbols & pictographs (2 of 2)
    u"(\ud83d[\ude80-\udeff])|"  # transport & map symbols
    u"(\ud83c[\udde0-\uddff])"  # flags (iOS)
    "+", flags=re.UNICODE)

def remove_emoji(text):
    return emoji_pattern.sub(r'', text)